/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bittorentlike;

import define.Define;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import org.bouncycastle.util.encoders.Hex;

/**
 *
 * @author Xuan Cau
 */
public class Split {
    private String _file_name;
    public Split(String file_name)
    {
        _file_name = file_name;
    }
    public void SplitFile()
    {
        try {
                File file = new File(_file_name);
                FileInputStream is = new FileInputStream(file);
                System.out.println("" + file.getName());
                FileOutputStream out_chunk = new FileOutputStream("torrent/" + file.getName() + ".torrent");
                
                byte[] chunk = new byte[Define.MAX_CHUNK];
                int count = 1;
                int count_size = 0;// = Define.MAX_CHUNK;
                /*if(Define.MAX_CHUNK < file.length())
                {
                    chunk = new byte[Define.MAX_CHUNK];
                    count_size = Define.MAX_CHUNK;
                }
                else
                    chunk = new byte[(int)file.length()];*/
                System.out.println("leng file = " + file.length());
                while (is.read(chunk) != -1) 
                {
                    count_size += Define.MAX_CHUNK;
                    System.out.println("total size file = " + count_size);
                    FileOutputStream out = new FileOutputStream("chunk/" + file.getName() + count + ".chunk");
                    out.write(chunk);
                    out.close();
                    byte[] sha1 = Util.Utils.SHA1(chunk);
                    chunk = new byte[Define.MAX_CHUNK];
                    /*if(count_size < file.length())
                        chunk = new byte[Define.MAX_CHUNK];
                    else
                        chunk = new byte[(int)file.length()-(count_size - Define.MAX_CHUNK)];*/
                    out_chunk.write(Util.Utils.intToByteArray(sha1.length));
                    out_chunk.write(sha1);
                    String s = "\n";
                    out_chunk.write(s.getBytes());
                    count ++;
                }
                out_chunk.close();
                System.out.println("done!");
            } 
            catch (FileNotFoundException fnfE) 
            {
                // file not found, handle case
            } 
            catch (IOException ioE) 
            {
                // problem reading, handle case
            }
    }
}
